Completed
Push — master ( fdd593...5aa3de )
by Andres
30s
created

angular.service(ꞌutilꞌ)   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
c 2
b 0
f 0
nc 4
dl 0
loc 16
rs 9.4285
nop 2
1
/* globals Ziggurat */
2
/* globals numberformat */
3
/**
4
 util
5
 Utility service with misc. functions.
6
7
 @namespace Services
8
 */
9
'use strict';
10
11
angular
12
  .module('game')
13
  .service('util', ['prettyNumberFilter',
14
    '$sce',
15
    'data',
16
    'state',
17
    function(prettyNumber, $sce, data, state) {
18
      this.gaussian = new Ziggurat();
19
20
      /* Return the HTML representation of an element, or the element itself
21
      if it doesn't have one */
22
      this.getHTML = function(resource) {
23
        let html = data.html[resource];
24
        if (typeof html === 'undefined' && data.resources[resource]) {
25
          html = data.resources[resource].html;
26
        }
27
        if (typeof html === 'undefined') {
28
          return resource;
29
        }
30
        return html;
31
      };
32
33
      this.prettifyNumber = function(number) {
34
        if (typeof number === 'undefined' || number === null) {
35
          return null;
36
        }
37
        if (number === '') {
38
          return '';
39
        }
40
        if (number === Infinity) {
41
          return '∞';
42
        }
43
        if (number === 0) {
44
          return '0';
45
        }
46
        return numberformat.format(number, state.player.numberformat);
47
      };
48
49
      this.randomDraw = function(number, p) {
50
        let production;
51
        let mean = number * p;
52
        // Gaussian distribution
53
        let q = 1 - p;
54
        let variance = number * p * q;
55
        let std = Math.sqrt(variance);
56
        production = Math.round(this.gaussian.nextGaussian() * std + mean);
57
        if (production > number) {
58
          production = number;
59
        }
60
        if (production < 0) {
61
          production = 0;
62
        }
63
        return production;
64
      };
65
66
      this.addResource = function(resource, key, quantity){
67
        resource.number += quantity;
68
        if (quantity > 0 && !resource.unlocked) {
69
          resource.unlocked = true;
70
          state.addNew(key);
71
        }
72
      }
73
74
      this.trustHTML = function(html) {
75
        return $sce.trustAsHtml(html);
76
      };
77
    }
78
  ]);
79